<?php


require_once("inc.member.php");





$this_title=__($vars["title"])." &raquo; ".__("Registration");


$page_title=replace_tag(__("<%title%> &raquo; ").__("Registration"), array("<%title%>"=>__($vars["title"])));


$content_title=__("Register");





$r_position=array(1,2);


$r_position_d=array(1=>__("Left"),2=>__("Right"));


$r_link=array($uid,0);


$r_link_d=array($uid=>__("Yes"),0=>__("No"));


$r_gender=array("m", "f");


$r_gender_d=array("m"=>__("Male"), "f"=>__("Female"));


$country_code=$vars['common']['country_code'];


array_shift($country_code);


$country_code_t=$vars['common']['country_code_text'];


foreach($country_code_t as $code=>$cname){


 $country_code_d[$code]=__($cname);


}


$r_payment_channel=array('eswallet','cwallet');


$r_payment_channel_d=array('eswallet'=>__($vars['eswallet_title'])." ".number_format($r_user['eswallet'], 2), 'cwallet'=>__($vars['cwallet_title'])." ".number_format($r_user['cwallet'], 2)." ".__("(Max 50%, balance will deduct from IP2)"), 'twallet'=>$r_user['twallet']." ".__("free 3 start account(s)"), 'fwallet'=>$r_user['fwallet']." ".__("free 5 start account(s)"));

$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;

$r_package=$vars['r_package'];

$r_package_d=$vars['r_package_detail'];


$td_width=175;





require_once("inc.register_tab.php");





//#####AJAX CALL#####


if($_GET["aj"] && $_GET["check_ref"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


		$ajerrmsg=replace_tag(__("Sponsor ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}





if($_GET["aj"] && $_GET["check_upline"]){


	if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal','n')"))){


		$ajerrmsg=replace_tag(__("Upline ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));


	}else{


		$ajmsg=replace_tag(__("Upline ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['username']));


	}


	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);


	print format_xml($xml);


	exit();


}


//#####END AJAX CALL#####





//#####REGISTER POST#####


if($_SESSION["user_register"] && $_POST["__req"]){


	/*##### ERROR CHECK #####*/

	$chk_arr="_name,_password,_email,_address,_mobileno,_bank_name,_bank_acc_no,_bank_swiftcode,_bank_branch";

	$chk_arr2=$chk_arr.",_username";
	$chk_arr2=explode(",", $chk_arr2);
	
	foreach($post_s as $f=>$v){


		if(in_array($f, $chk_arr2)){


			$data[$f]=$v;


		}


	}

	if($post_s["main_link"]==0)
		$errmsg=verify_form_data("users2", $data);
	else
		$errmsg=verify_form_data("users", $data);


	if(!$errmsg){


		//check referrer


		if($post_s["ref"]){


			if(!$r_ref=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[ref]' and status in ('suspended','normal')"))){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}elseif($r_ref['activated'] != 'y'){


				$errmsg.=replace_tag(__("Sponsor ID: '<%rid%>' is not activated and cannot sponsor new member."), array("<%rid%>"=>$post_h['ref']))."<br />\n";


			}else{


				$ref_found=1;


				$ref_id=$r_ref["id"];


			}


		}else{


			$ref_id=0;


		}


		//check placement


		if($post_s["matrix_upline"]){


			if(!$r_upline=@mysql_fetch_assoc(mysql_query("select * from $db->users where code='$post_d[matrix_upline]' and status in ('suspended','normal','n')"))){


				$errmsg.=replace_tag(__("Placement ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['matrix_upline']))."<br />\n";


			}else{
				$matrix_upline_info=get_user_detail_by_code($post_d['matrix_upline']);

				if(!in_array($post_s['matrix_position'], $r_position)){


					$errmsg.=__("Please select a placement position.")."<br />";


				}elseif(@mysql_num_rows(mysql_query("select * from $db->users where matrix_upline='$matrix_upline_info[id]' and matrix_position='$post_d[matrix_position]'"))){


					$errmsg.=__("The selected Placement ID and Placement Position is already occupied.")."<br />";


				}else{
					
					$matrix_upline_id = $matrix_upline_info["id"];
					
				}


			}


		}else{


			$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Upline ID")))."<br />";


		}


		if(!$errmsg){


			if($post_s['matrix_upline'] != $post_s['ref'] ){
				
				$sponsor = get_user_detail_by_code($post_s['ref']);
				$placement = get_user_detail_by_code($post_s['matrix_upline']);
				
				if(!is_group_matrix_downline_of($placement['id'], $sponsor['id'])){
					
					$errmsg.=__("The selected Upline ID is not in the network group of the Sponsor ID.")."<br />";	
					
				}

			}


		}

		
		if(!in_array($post_s['package'], $r_package)){


			$errmsg.=__("Please select an activation package.")."<br />";


		}


		if(!in_array($post_s['payment_channel'], $r_payment_channel)){


			$errmsg.=__("Please select a payment channel.")."<br />";


		}else{
			
			$cost = $vars['package'][$post_s['package']]['price'];
			$bv = $vars['package'][$post_s['package']]['bv'];
			
			if($post_s['payment_channel'] == 'ewallet' || $post_s['payment_channel'] == 'dwallet') $deduct_amount = $cost;
			else $deduct_amount = $bv;
					
			if($post_s['payment_channel'] == 'dwallet'){
				if($r_user['dwallet'] <= 0){	
					$errmsg.=replace_tag(__("You do not have sufficient <%title%> to activate this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
				}else{
					
				}
			}else{
				if($r_user[$post_s['payment_channel']] < $deduct_amount){	
					$errmsg.=replace_tag(__("You do not have sufficient <%title%> to activate this package."), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($deduct_amount, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment_channel'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment_channel']], 2)))."<br />\n";
				}
			}	
			
		}


		if($post_s["acc_type"]=="p"){



			//check dob


			$dob="$post_s[dob_year]-".pad_length($post_s["dob_month"], 2)."-".pad_length($post_s["dob_day"], 2);


			if(!@checkdate($post_s["dob_month"], $post_s["dob_day"], $post_s["dob_year"])){


				$errmsg=__("Invalid date format selected for DOB.")."<br />\n";


			}


			//check gender


			if(!in_array($post_s["gender"], $r_gender)){


				$errmsg.=__("Please specify Gender.")."<br />\n";


			}


		}elseif($post_s["acc_type"]=="c"){


			//check business reg no


			if(bis_reg_found($post_d["_bis_reg"])){


				$errmsg.=replace_tag(__("Company Reg. No. '<%bis_reg%>' belongs to another member."), array("<%bis_reg%>"=>$post_h['_ic']))."<br />\n";


			}


		}


		//check username


		if(username_found($post_d["_username"])){


			$errmsg.=replace_tag(__("The username '<%username%>' is not available, please choose another."), array("<%username%>"=>$post_h["_username"]))."<br />\n";


		}


		//check password


		if($post_s["_password"] != $post_s["password3"]){


			$errmsg.=__("Your entered level 1 password did not match.")."<br />\n";


		}
		
		if($post_s["password2"] != $post_s["password4"]){


			$errmsg.=__("Your entered level 2 password did not match.")."<br />\n";


		}

		//check email


		if(strlen($post_s['_email'])){


			if(!verify_email($post_s["_email"])){


				$errmsg.=__("Please provide a valid email address.")."<br />\n";


			}


		}


		//check terms


		if(!$post_s["terms"]){


			$errmsg.=replace_tag(__("You must agree to the Terms of Service of <%title%>."), array("<%title%>"=>__($vars["title"])))."<br />\n";


		}


	}


	//#####END ERROR CHECK#####





	$preview = $confirm = false;


	if(!$errmsg){


		if(!$post_s['__confirm'] && !$post_s['__edit']){


			$preview = true;


		}elseif($post_s['__confirm']){


			$confirm = true;


		}


	}





	//#####ADD TO DB#####


	if(!$errmsg && $confirm){


		$field_arr=$chk_arr2;


		for($i=0,$t=count($field_arr);$i<$t;$i++){
			
			if(substr($field_arr[$i], 1)=='signup_code') continue;

			$ufq.=($ufq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i]);


			$uvq.=($uvq? ", " : "")."'".$post_d[$field_arr[$i]]."'";


		}


		$ufq.=", dob, gender";


		$uvq.=", '$dob', '$post_d[gender]'";


		$salt=generate_random_code(32);
		$enc_pass=md5($post_s["_password"].$salt).":".$salt;

		$password2=generate_random_code(6);
		$ewallet_enc_pass=md5($password2.$salt).":".$salt;
		
		$password3=generate_random_code(6);
		$epoint_enc_pass=md5($password3.$salt).":".$salt;

		$status='normal';


		$vc=generate_random_code(20);


		$rank_a = $purchase['rank_a'];
		$total_account = $vars['package'][$purchase['rank_a']]['account']; //use?
		$pool_share = $vars['package'][$purchase['rank_a']]['cp'];
		
		$datetime=ndate($vars["system_date_format"]);

		$is_free = '0';
		
		if($post_s["main_link"]<>0)
			$sql="insert into $db->users (acc_type, is_stockist, ref, creator, cid, rank_a, matrix_upline, matrix_position, $ufq, main_uid, country, status, is_free, activated, activated_date, cdate, pool_share) values ('$post_d[acc_type]', 'n', '$ref_id', 'u', '$uid', '$rank_a', '$matrix_upline_id', '$post_d[matrix_position]', $uvq, '$post_d[main_link]', '$post_d[country]', '$status', $is_free, 'y', '$datetime', '$datetime', '$pool_share')";
		else
			$sql="insert into $db->users (acc_type, is_stockist, ref, creator, cid, rank_a, matrix_upline, matrix_position, $ufq, ewallet_password, epoint_password, enc_password, ewallet_enc_password, epoint_enc_password, country, status, is_free, activated, activated_date, cdate, pool_share) values ('$post_d[acc_type]', 'n', '$ref_id', 'u', '$uid', '$rank_a', '$matrix_upline_id', '$post_d[matrix_position]', $uvq, '$password2', '$password3', '$enc_pass', '$ewallet_enc_pass', '$epoint_enc_pass', '$post_d[country]', '$status', $is_free, 'y', '$datetime', '$datetime', '$pool_share')";
			//$sql="insert into $db->users (acc_type, is_stockist, ref, creator, cid, rank_a, matrix_upline, matrix_position, $ufq, ewallet_password, epoint_password, enc_password, ewallet_enc_password, epoint_enc_password, country, status, is_free, activated, activated_date, cdate, pool_share) values ('$post_d[acc_type]', 'n', '$ref_id', 'u', '$uid', '$rank_a', '$matrix_upline_id', '$post_d[matrix_position]', $uvq, '$post_s[_password]', '$post_s[_password]', '$enc_pass', '$enc_pass', '$enc_pass', '$post_d[country]', '$status', $is_free, 'y', '$datetime', '$datetime', '$pool_share')";

		if(!mysql_query($sql)){


			$errmsg.=__("We have encountered some error and the registration process has been failed.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");


		}else{
			
			$new_uid=mysql_insert_id();
			$array_matrix_upline[0] = $new_uid;
			$matrix_upline = $new_uid;				

			
			if(!mysql_query("update $db->users set $post_s[payment_channel]=$post_s[payment_channel]-$deduct_amount where id='$uid' limit 1")){
				

				$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} could not be deducted with ".number_format($deduct_amount, 2)." for activation cost.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";


			}else{
				

				$wallet_descr = mysql_real_escape_string("Debited $vars[currency]".number_format($deduct_amount, 2)." for registering new member with ID#$dist_code for package {$r_package_d[$post_s['package']]}.");


				if(!mysql_query($sql="insert into ".$vars["dbi"]["prefix"]."member_$post_s[payment_channel]_record (uid, type, amount, descr, cdate) values ('$uid', 'd', '$deduct_amount', '$wallet_descr', '$datetime')")){


					$critical_error.="Error occur while member id#".$r_user['code']." register a new member id#$dist_code, the user #$uid {$vars[$post_s['payment_channel'].'_title']} has been deducted with ".number_format($deduct_amount, 2)." but the transaction history could not be recorded.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";


				}else{


					$new_eid = mysql_insert_id();


					$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);


					if(!$last_bal){


						$last_bal = 0;


					}


					$last_bal -= $deduct_amount;


					@mysql_query("update {$vars["dbi"]["prefix"]}member_$post_s[payment_channel]_record set bal='$last_bal' where id='$new_eid' limit 1");


				}


			}


			


			//insert purchase record


			$first_sale = true;


			$total_bv = $total_dp = $total_rp = $vars['package'][$post_s['package']]['bv'];
			$price = $vars['package'][$post_s['package']]['price'];
			$total_cp = $vars['package'][$post_s['package']]['cp'];
			$voucher_amount = $price * ($total_cp/100);			
			$incentive_balance = $vars['package'][$post_s['package']]['incentive'];
			$incentive_amount = (floor(($incentive_balance/720)*100))/100;
			
			$share_price = @mysql_result(mysql_query("select value from {$vars["dbi"]["prefix"]}settings where param='share_price' limit 1"), 0);
			if($share_price<0) $share_price = 0;

			$payment_channel = $post_s['payment_channel'];
			
			if($payment_channel=='twallet' || $payment_channel=='fwallet')
				$no_bv = 'y';
			else 
				$no_bv = 'n';
				
			if($payment_channel=='ewallet' || $payment_channel=='eswallet' || $payment_channel=='cwallet'){
				$collected = 'y';
				$collected_date = date('Y-m-d H:i:s');
				$incentive_date = date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')+30, date('Y')));				
			}else{
				$collected = 'n';
				$collected_date = '0000-00-00 00:00:00';
				$incentive_date = '0000-00-00';
			}
			
			//for those special case, get register point but no bonus payout
			$refund_bv = @mysql_result(mysql_query("select refund_bv from $db->users where id='$uid'"), 0) or 0;
			if($refund_bv>0 && $payment_channel=='eswallet'){
				mysql_query("update $db->users set dividend_count=0, owallet='$total_bv' where id='$new_uid'");
				
				mysql_query("update $db->users set refund_bv=refund_bv-".$total_bv." where id='$uid'");
				$total_bv = 0;	
				$share_price = 0;			
			}
			
			if(!mysql_query($sql="insert into $db->purchase (creator, cid, uid, stockist_sale, member_sale, no_bv, amount, total_bv, total_dp, total_rp, total_cp, share_price, payment_type, first_sale, collected, rank_a, status, cdate, edate) values ('u', '$uid', '$new_uid', 'n', 'y', '$no_bv', '$cost', '$total_bv', '$total_dp', '$total_rp', '$total_cp', '$share_price', '$payment_channel', 'y', 'n', '$rank_a', 'confirmed', '$datetime', '$datetime')")){


				$critical_error.="Error creating the member purchase record when member ID #$uid register another member id#$new_uid. Please manually execute the SQL below to record the transaction:\n\n$sql\n\nError: ".mysql_error()."\n";


				$pid="0";


			}else{

				$pid=mysql_insert_id();
				
				if($total_bv>0){
					//20% credit to cashflow
					$cashflow = @mysql_result(mysql_query("select value from $db->settings where param='cashflow' limit 1"), 0);
					$cashflow += $total_bv*0.2;
					mysql_query("update $db->settings set value=".$cashflow." where param='cashflow'");
					$sql = "INSERT INTO gg_cashflow SET sid=".$pid.",type='credit',amount='".($total_bv*0.2)."',bal='".$cashflow."',cdate='".date('Y-m-d H:i:s')."'";
					mysql_query($sql);
				}
				
				$sale_refno = $refno = "MS" . str_pad($pid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);


				if(!mysql_query($sql="update $db->purchase set refno='$refno' where id='$pid' limit 1")){


					$sale_errmsg.=__("Error recording the sale reference number. Please manually record the sale reference number by executing SQL.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";


					$sale_errlog.="Error recording the sale reference number. Please manually record the sale reference number by executing SQL.<br />\n<br />\nSQL: $sql\n\nError: ".mysql_error()."\n";


				}


				//insert sales detail


				$purchased_prods[$post_s['package']] = 1;


				foreach($purchased_prods as $refno => $qty){


					$this_cost=$cost;


					$this_bv=$total_bv;


					if(!mysql_query($sql="insert into $db->purchase_detail (slid, refno, title, prod_type, qty, amount, bv, dp, rp, total, total_bv) values ('$pid', '".AddSlashes($refno)."', '".AddSlashes($r_package_d[$refno])."', 'n', '$qty', '$cost', '$total_bv', '$total_dp', '$total_rp', '$this_cost', '$this_bv')")){


						$critical_error.="Error creating the member sales detail when member ID #$uid register another member id#$new_uid. Please manually execute the SQL below to record the sales detail.\n\nSQL: $sql\n\nError: ".mysql_error()."\n\n";


					}


				}


			}

			$activation_link="<a href='".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]'>".M_URL."/$activation_file?vc=$vc&email=$post_s[_email]</a>";


			//email user


			$msg_style=$vars["css"]["msg_style"];


			$td_style=$vars["css"]["td_style"];


			$td_title_style=$vars["css"]["td_title_style"];


			$u_sub="$vars[title] - Thank You for Your Registration";

			$user_info=get_user_detail_by_id($new_uid);
			
			$user_table="
			

			<table align='center' ".$vars["css"]["table_style"]." width='100%'>


				<tr>


					<td $td_title_style colspan='2'>".__("Account Information")."</td>


				</tr>


				<tr>


					<td $td_style>".__("Registered Screen Name")."</td>


					<td $td_style>$post_s[_username]</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 1 Password")."</td>


					<td $td_style>$post_s[_password]</td>


				</tr>


				<tr>


					<td $td_style>".__("Level 2 Password")."</td>


					<td $td_style>$post_s[password2]</td>


				</tr>


				<tr>


					<td $td_style colspan=2>".__("From RMC Administration Robot")."</td>


				</tr>


				<tr>


					<td $td_style colspan=2>".__("Note: Please do not reply to this message as it will be automatically discarded.")."</td>


				</tr>


			</table>";
			
			if($post_s["main_link"]==0){
			
				$user_table2="
	
	
				<table align='center' ".$vars["css"]["table_style"]." width='100%'>
	
	
					<tr>
	
	
						<td $td_title_style colspan='2'>".__("Account Information")."</td>
	
	
					</tr>
	
	
					<tr>
	
	
						<td $td_style width='120'>".__("User ID")."</td>
	
	
						<td $td_style>$user_info[code]</td>
	
	
					</tr>
	
	
				</table>";
				
			}else{
				
				$user_table2="
	
	
				<table align='center' ".$vars["css"]["table_style"]." width='100%'>
	
	
					<tr>
	
	
						<td $td_title_style colspan='2'>".__("Account Information")."</td>
	
	
					</tr>
	
	
					<tr>
	
	
						<td $td_style>".__("Registered Screen Name")."</td>
	
	
						<td $td_style>$post_s[_username]</td>
	
	
					</tr>
	
	
					<tr>
	
	
						<td $td_style>".__("Level 1 Password")."</td>
	
	
						<td $td_style>$post_s[_password]</td>
	
	
					</tr>
	
	
					<tr>
	
	
						<td $td_style>".__("Level 2 Password")."</td>
	
	
						<td $td_style>$post_s[password2]</td>
	
	
					</tr>
	
	
				</table>";
				
			}


			$u_msg=


			"<p $msg_style>Dear $post_s[_name], <br />\n<br />\nThank you for your registration. The user information for your new account is listed below:</p>


			$user_table";

			if($post_s["main_link"]<>0){
				if(email_user($post_s["_email"], $u_sub, $u_msg)){
	
	
					$email_msg=replace_tag(__("A welcome email has been sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));
	
	
				}else{
	
	
					$email_errmsg=replace_tag(__("The Welcome email could not be sent to '<%email%>', please contact us for more information."), array("<%email%>"=>$post_h['_email']));
	
	
				}
			}




			//email referrer


			if($post_s["ref"] && $post_s["main_link"]<>0){


				$r_sub=$vars["title"]." - You have just sponsored a new member in your downline group!";


				$r_msg=


				"<p>Dear $r_ref[name],</p>


				<p>Congratulations! You have just sponsored a new member in your downline group. The member details of your new downline are as below:</p>


				<p>Downline ID: $user_info[code]<br />\nName: $user_info[name]</p>


				<p>You can check your network <a href='".M_URL."/members/".$vars["file"]["member"]["genealogy"]."'>here</a>. Keep up the good work!</p>";


				email_user($r_ref["email"], $r_sub, $r_msg);


			}


		}


		if(!$errmsg){


			$_SESSION["user_register"]=false;

			if($post_s["main_link"]<>0)
				$msg=__("Thank you for your registration.")."<br />\n";
			else
				$msg=__("Thank you for your registration.")." ".($email_msg? $email_msg : "<span class='red'>$email_errmsg</span>")."<br />\n";


			print format_member_page(str_replace("<%tab_content%>", "<h2>$page_title</h2>".format_msg($msg)."<p>".__("The user information of your account is listed below:")."</p>$user_table2", $tab), $this_title, $content_title, $css);


			exit();


		}


	}





	$errmsg=$errmsg? format_err($errmsg) : "";


	


	if($critical_error){echo $critical_error;


		$a_sub = "$vars[title] - User Registration Error";


		$a_msg = 


		"<p>Dear admin,</p>


		<p>Error occur while member id#$uid register a new member, error below:</p>


		$critical_error";


		email_admin($a_sub, $a_msg, 'e');


	}


}


$_SESSION["user_register"]=true;

$link_select=build_select($r_link, $r_link_d, $post_s["main_link"]+0, 'main_link', $inputbox_style." onchange='displayreentry()' id='main_link'");

if($post_s["reentry"]=='1' || $get_s["reentry"]=='1'){
	$r_user=get_user_detail_by_id($uid);
	$dob = split('-',$r_user["dob"]);
	$form_fields=array("acc_type"=>"p","ref"=>$r_user['code'],"matrix_upline"=>$r_user['code'],"matrix_position"=>"","payment_channel"=>"ewallet","package"=>"","_person_in_charge"=>"","_bis_reg"=>"","_username"=>"","_name"=>$r_user['name'],"_password"=>"","password2"=>"","password3"=>"","password4"=>"","_email"=>$r_user['email'],"_ic"=>$r_user['ic'],"_address"=>$r_user[''],"country"=>$r_user['country'],"_homeno"=>$r_user['homeno'],"_mobileno"=>$r_user['mobileno'],"dob_day"=>$dob[2],"dob_month"=>$dob[1],"dob_year"=>$dob[0],"gender"=>$r_user['gender'],"_bank_name"=>$r_user['bank_name'],"_bank_acc_no"=>$r_user['bank_acc_no'],"_bank_swiftcode"=>$r_user['bank_swiftcode'],"_bank_branch"=>$r_user['bank_branch'],"terms"=>"");
	
	$link_content="<tr>


			<td>".__("Link with main account").__(":")." ".__("*")."</td>


			<td>$link_select</td>


		</tr>";
}else{
	$form_fields=array("acc_type"=>"p","ref"=>$r_user['code'],"matrix_upline"=>$r_user['code'],"matrix_position"=>"","payment_channel"=>"ewallet","package"=>"","_person_in_charge"=>"","_bis_reg"=>"","_username"=>"","_name"=>"","_password"=>"","password2"=>"","password3"=>"","password4"=>"","_email"=>"","_ic"=>"","_address"=>"","country"=>"HK","_homeno"=>"","_mobileno"=>"","dob_day"=>"","dob_month"=>"","dob_year"=>"","gender"=>"m","_bank_name"=>"","_bank_acc_no"=>"","_bank_swiftcode"=>"","_bank_branch"=>"","terms"=>"");
	$link_content="";	
}




foreach($form_fields as $field => $default){


	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


	$dis[$field]=!$posting? $default : $post_h[$field];


}


if($get_s["pos"]){
	$dis['matrix_position'] = $get_s["pos"];
}

if($get_s["upline"]){
	$dis['matrix_upline'] = $get_s["upline"];
}


$position_select=build_select($r_position, $r_position_d, $dis['matrix_position'], 'matrix_position', "class='form-control'");


$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", "class='form-control'");


$gender_select=build_select($r_gender, $r_gender_d, $dis["gender"], "gender", "class='form-control'");


$dob_input=generate_dmy_input("dob", $dis["dob_day"], $dis["dob_month"], $dis["dob_year"], "class='form-control'");


$payment_channel_select=build_select($r_payment_channel, $r_payment_channel_d, $dis['payment_channel'], 'payment_channel', "class='form-control'");


$package_select=build_select($r_package, $r_package_d, $dis['package'], 'package', "class='form-control'");





//referrer


if($dis["ref"]){


	if($r=get_user_detail_by_code($dis["ref"])){


		$ref_text="<span class='bold'>".replace_tag(__("Sponsor ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["name"]))."</span>";


	}else{


		$ref_text="<span class='red'>".__("Invalid Sponsor")."</span>";


	}


}


if($dis["matrix_upline"]){


	if($r=get_user_detail_by_code($dis["matrix_upline"])){


		$up_text="<span class='bold'>".replace_tag(__("Upline ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$r["code"], "<%name%>"=>$r["username"]))."</span>";


	}else{


		$up_text="<span class='red'>".__("Invalid Upline")."</span>";


	}


}





//javascript


$jvscript=


"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>


<script type='text/javascript'>


jQuery(document).ready(function(j){


 j('form[@name=member_form],form[@name=member_form2]').submit(function(){


  j('input[@name=submit_btn]').attr('disabled','disabled');


 });





 j('input#check_ref_btn').click(function(){


  j('span#ref_text').html('').removeClass('red');


  if(j('input[@name=ref]').val()==''){


   j('span#ref_text').html('".AddSlashes(__("Please provide a Sponsor ID!"))."').addClass('red');


  }else{


   j('span#ref_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_ref=1',


    data: {'ref': j('input[@name=ref]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#ref_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#ref_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_ref_btn').attr('disabled','');


    }


   });


  }


 });


 


 j('input#check_up_btn').click(function(){


  j('span#up_text').html('').removeClass('red');


  if(j('input[@name=matrix_upline]').val()==''){


   j('span#up_text').html('".AddSlashes(__("Please provide a Upline ID!"))."').addClass('red');


  }else{


   j('span#up_text').html('Checking...');


   j(this).attr('disabled','disabled');


   j.ajax({


    url: '$this_file?aj=1&check_upline=1',


    data: {'ref': j('input[@name=matrix_upline]').val()},


    type: 'post',


    dataType: 'xml',


    error: function(){


     j('span#up_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');


    },


    success: function(data){


     var mesg='';


     if(j('loggedout', data).text()=='loggedout'){


      mesg='".AddSlashes(__("You have been logged out."))."';


     }else{


      j(data).find('msg').each(function(){


       mesg+=j(this).text()+' ';


      });


     }


     var status=j(data).find('status').text();


     j('span#up_text').html(mesg).addClass(status==1? 'bold' : 'red');


    },


    complete: function(){


     j('input#check_up_btn').attr('disabled','');


    }


   });


  }


 });


});





function update_acc_type(type){


 if(type=='p'){


  personal_d='block';


  company_d='none';


 }else{


  personal_d='none';


  company_d='block';


 }


 q('acctype_personal').style.display=personal_d;


 q('acctype_personal_home').style.display=personal_d;


 q('acctype_company').style.display=company_d;


}





function goback(){


	q('__edit').value = 1;


	q('__confirm').value = '';


	document.member_form2.submit();


}

function MM_openBrWindow(theURL,features) {
	//var width_height = features.split(',');	
  	//var lf = (screen.width - 480)/2;
	//var tf = (screen.height - 350)/2;
	//var sizeIt = 'width=400,height=250,scrollbars=yes,resizable=no,top='+tf+',left='+lf;
	//win = window.open(theURL,'mywindow',sizeIt);
	//if (window.focus) 
	//{
	//	win.focus();
	//}
}

function displayreentry(){
	var a = document.getElementById('main_link');
	if(a.options[a.selectedIndex].value == '0'){
		document.getElementById('isreentry').style.display = '';
	}else{
		document.getElementById('isreentry').style.display = 'none';
	}
}

</script>";





//content jvscript


$c_jvscript=


"<script type='text/javascript'>


update_acc_type('$dis[acc_type]');


</script>";





$display_fields=array("ref","matrix_upline","_person_in_charge","_bis_reg","_username","_name","_password","_email","_ic","_address","_homeno","_mobileno","_bank_name","_bank_acc_no","_bank_swiftcode","_bank_branch");


foreach($form_fields as $field => $default){


	if(in_array($field, $display_fields)){


		$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;


		$dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);


		$readonly=$textarea=$password=false;


		if(!$preview){


			if($field=='matrix_upline'){


				$readonly=true;


			}elseif($field=='_bank_branch'){


				$extra_display="<tr><td></td><td><table><tr><td><input type='checkbox' name='terms' ".($dis["terms"]? "checked='checked'" : "")." id='chk_terms' onchange='MM_openBrWindow(\"/tnc.html\",\"width=480,height=600\")'/></td><td><label for='chk_terms'>".replace_tag(__("I have read and agreed to the <%link%>Terms of Service<%/link%> of <%title%>."), array("<%link%>"=>"<a href='".$vars["file"]["public"]["terms"]."' target='_blank'>", "<%/link%>"=>"</a>", "<%title%>"=>__($vars["title"])))."</label></td></tr></table></td></tr>";


			}else{


				$extra_display='';


			}


		}else{


			$extra_display='';


		}


		if(in_array($field, array("_password","_sec_password"))){


			$password=true;


		}


		$readonly_str=$readonly? "readonly='readonly'" : "";


		$form_inputfield[$db_fieldname]="


		<tr id='input_$db_fieldname'>


			<td width='$td_width'><div style='width:".$td_width."px;'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</div></td>


			<td>".($preview? ($dis[$field]? $dis[$field] : '&nbsp;') : ($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "


			<input type='".($password? "password" : "text")."' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />"))."$extra_display</td>


		</tr>";
		
		
		$form_inputfield[$db_fieldname]='
		  	<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__($dbr[4]).'</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="'.$field.'" name="'.$field.'" value="'.$dis[$field].'">
			</div>
			</div>';


	}


}





//##### PREVIEW #####


if($preview){


	foreach($post_h as $f=>$v){


		$hidden_fields.="<input type='hidden' name=\"$f\" value=\"$v\" />\n";


	}


	$register="


	<form name='member_form2' method='post' action='$this_file'>


	<input type='hidden' name='__req' value='1' />


	<input type='hidden' name='__edit' />


	<input type='hidden' name='__confirm' value='1' />


	$hidden_fields


	<p>".__('Please review your particulars and when you are confirm please click the Register button.')."</p>


	<table class='pbt_table rev'>


		<tr class='pbt_header'>


			<td colspan='2'>".__("Account Information")."</td>


		</tr>  

		<tr>


			<td>".__("Package").__(":")." ".__("*")."</td>


			<td>".$vars['rank_index_a_d'][$purchase["rank_a"]]."</td>


		</tr>


		<tr style='display:none'>


			<td>".__("Account Type").__(":")." ".__("*")."</td>


			<td>".($dis['acc_type']=="p"? __("Personal") : __("Company"))."</td>


		</tr>


		$form_inputfield[ref]


		$form_inputfield[matrix_upline]


		<tr>


			<td>".__("Placement Position").__(":")." ".__("*")."</td>


			<td>$dis[matrix_position]</td>


		</tr>

<tbody style='display:none'>	
		$form_inputfield[username]


		<tr>


			<td>".__("Password").__(":")." ".__("*")."</td>


			<td><span class='italic'>".__("Not Displayed")."</td>


		</tr>


		$form_inputfield[name]


		$form_inputfield[email]".($dis['acc_type']=='p'? "


		$form_inputfield[ic]


		<tr>


			<td>".__("Gender").__(":")." ".__("*")."</td>


			<td>{$r_gender_d[$dis['gender']]}</td>


		</tr>


		<tr>


			<td>".__("Date of Birth").__(":")." ".__("*")."</td>


			<td>$dis[dob_day]-$dis[dob_month]-$dis[dob_year]</td>


		</tr>" : "


		$form_inputfield[bis_reg]


		$form_inputfield[person_in_charge]")."


		$form_inputfield[address]


		<tr>


			<td>".__("Country").__(":")." ".__("*")."</td>


			<td>{$country_code_d[$dis['country']]}</td>


		</tr>".($dis['acc_type'] == 'p'? "


		$form_inputfield[homeno]" : "")."


		$form_inputfield[mobileno]


		<tr class='pbt_header'>


			<td colspan='2'>".__("Payment Information").__(":")." ".__("*")."</td>


		</tr>


		$form_inputfield[bank_name]


		$form_inputfield[bank_acc_no]


		$form_inputfield[bank_swiftcode]


		$form_inputfield[bank_branch]

</tbody>
	</table>


	<table class='pbt_table'>


		<tr>


			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>


			<input type='button' name='back_btn' value=\"".__("Back")."\" onclick=\"goback();\" />


			<input type='submit' name='submit_btn' value=\"".__("Register")."\" />


			</td>


		</tr>


	</table>";


	//##### FIRST TIME #####


}else{
	
	$register=($errmsg?"$errmsg" : "").'
			<div class="panel panel-primary">
				      <form class="form-horizontal" name="member_form" method="post" action="'.$this_file.'">
					  <input type="hidden" name="__req" value="1" />
				      <div class="panel-heading">
				          <h4>'.__("New Register").'</h4>				          
				      </div>
				      <div class="panel-body">'.
						$form_inputfield['ref'].
						$form_inputfield['matrix_upline'].
					'<div class="form-group">
						  	<label for="selector1" class="col-sm-3 control-label">'.__('Placement Position').'</label>
						  	<div class="col-sm-6">'.$position_select.'</div>
					</div>
					<div class="form-group">
						<label for="selector1" class="col-sm-3 control-label">'.__('Activation Package').'</label>
						<div class="col-sm-6">'.$package_select.'</div>
					</div>
					<div class="form-group">
						<label for="selector1" class="col-sm-3 control-label">'.__('Payment').'</label>
						<div class="col-sm-6">'.$payment_channel_select.'</div>
					</div>'.
						$form_inputfield['username'].
						$form_inputfield['password'].
					'<div class="form-group">
						<label for="disabledinput" class="col-sm-3 control-label">'.__('Confirm Level 1 Password').'</label>
						<div class="col-sm-6">
							<input type="password" class="form-control" id="password3" name="password3" value="'.$dis['password3'].'">
						</div>
					</div>
					<div class="form-group">
						<label for="disabledinput" class="col-sm-3 control-label">'.__('Level 2 Password').'</label>
						<div class="col-sm-6">
							<input type="password" class="form-control" id="password2" name="password2" value="'.$dis['password2'].'">
						</div>
					</div>
					<div class="form-group">
						<label for="disabledinput" class="col-sm-3 control-label">'.__('Confirm Level 2 Password').'</label>
						<div class="col-sm-6">
							<input type="password" class="form-control" id="password4" name="password4" value="'.$dis['password4'].'">
						</div>
					</div>'.
						$form_inputfield['name'].
						$form_inputfield['email'].
						$form_inputfield['ic'].
					'<div class="form-group">
						<label for="selector1" class="col-sm-3 control-label">'.__('Gender').'</label>
						<div class="col-sm-6">'.$gender_select.'</div>
					</div>
					<div class="form-group">
						<label for="selector1" class="col-sm-3 control-label">'.__('Date of Birth').'</label>
						<div class="col-sm-6">'.$dob_input.'</div>
					</div>'.
						$form_inputfield[address].
					'<div class="form-group">
						<label for="disabledinput" class="col-sm-3 control-label">'.__('Country').'</label>
						<div class="col-sm-6">'.$country_select.'</div>
					</div>'.
						$form_inputfield[homeno].
						$form_inputfield[mobileno].
						$form_inputfield[bank_name].
						$form_inputfield[bank_acc_no].
						$form_inputfield[bank_swiftcode].
						$form_inputfield[bank_branch].
					'<div class="form-group">
						    <label for="disabledinput" class="col-sm-3 control-label">'.__('Level 2 Password').'</label>
						    <div class="col-sm-6">
						      <input type="password" class="form-control" id="password" name="password" placeholder="'.__('Need provide level 2 password to create new register').'">
						    </div>
						  </div>					  
				      </div>
				      <div class="panel-footer">
				      	<div class="row">
				      		<div class="col-sm-6 col-sm-offset-3">
				      			<div class="btn-toolbar">
					      			<input type="submit" name="submit_btn" value="'.__("Register").'"/>
				      			</div>
				      		</div>
				      	</div>
				      </div>
				  </form>
				  </div>
'.$c_jvscript;



}





$css.="


<style type='text/css'>


td{


	font-size:12px;


}





table.rev td{


	border:1px solid #000;


}


</style>";





$content=$register;


//$content=str_replace("<%tab_content%>", $content, $tab);



print format_member_page($content, $this_title, $content_title, $css.$jvscript);

?>